<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商铺编号" prop="shopsId">
        <!-- <HouseInput v-model="queryParams.code" type="house"/> -->
        <el-input
          v-model="queryParams.shopsId"
          placeholder="请输入商铺编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="hirerId">
        <el-input
          v-model="queryParams.hirerId"
          placeholder=""
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['feeSettings:rentalcontract:add']"
          >添加</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addHire(0)"
          v-hasPermi="['feeSettings:rentalcontract:add']"
          >默认收费项（出租）</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="addHire(1)"
          v-hasPermi="['feeSettings:rentalcontract:edit']"
          >默认收费项（出售）</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="rentalcontractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center" prop="id" />

      <el-table-column label="商铺编号" align="center" prop="shopsCode" />
      <el-table-column label="使用状态" align="center" prop="type" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type===0">已出租</el-tag>
          <el-tag type="danger" v-else>已出售</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="类别【数据字典】" align="center" prop="type" /> -->
      <el-table-column label="公司名" align="center" prop="hirerCompany" />
      <el-table-column label="姓名" align="center" prop="hirerName" />
      <el-table-column label="电话" align="center" prop="hirerPhone" />
      <el-table-column label="租金" align="center" prop="rent" />
      <el-table-column label="行业" align="center" prop="trade" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="合同状态" align="center" prop="state" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state===0">生效中</el-tag>
          <el-tag type="warning" v-else-if="scope.row.state===1">撤销</el-tag>
          <el-tag type="danger" v-else>逾期</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['feeSettings:rentalcontract:edit']"
            >编辑合同</el-button
          >


          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="putState(scope.row)"
            v-hasPermi="['feeSettings:rentalcontract:edit']"
            >撤销合同</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改租售合同对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      height="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-steps :active="active" align-center>
        <el-step title="步骤1" description="确认店铺信息"></el-step>
        <el-step title="步骤2" description="选择业主"></el-step>
        <el-step title="步骤3" description="设置费用"></el-step>
      </el-steps>
      <el-form
        v-if="this.active === 1"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="padding: 20px"
      >
        <el-form-item v-if="this.allId==''" label="商业区：" >
          <el-select v-model="form.dId" placeholder="请选择" @change="sGetList">
            <el-option
              v-for="item in downtownList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!-- <el-button @click="sGetList">搜索</el-button> -->
        </el-form-item>

         <el-form-item v-else label="商业区：">
          <el-select disabled v-model="this.download.downtownName"  placeholder="请选择">
          </el-select>
        </el-form-item>


        <el-form-item v-if="this.allId==''" label="编号：">
          <el-select  v-model="form.shopsCode" placeholder="请选择" @change="codesGetList">
            <el-option
              v-for="item in codes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!-- <el-button @click="codesGetList">搜索</el-button> -->
        </el-form-item>



         <el-form-item v-else label="编号：">
          <el-select disabled v-model="form.shopsCode" placeholder="请选择">
            <el-option
              v-for="item in codes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>



        <el-form-item v-if="this.allId==''"  label="类别：">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in types"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item v-else  label="类别：">
          <el-select disabled v-if="this.form.type==0" placeholder="出租">
            <el-option
              v-for="item in types"
              :key="item.value"   
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-select disabled v-else placeholder="出售">
            <el-option
              v-for="item in types"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="开始时间：" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item v-if="this.form.type!=1" label="出租时长(月): " prop="taxi">
          <el-input v-model="form.taxi" placeholder="请输入出租时长(月)">
            <template slot="append">月</template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="this.form.type!=1" label="租金：" prop="rent">
          <el-input v-model="form.rent" placeholder="请输入租金 ">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>

      <el-form
        v-else-if="this.active === 2"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="padding: 20px"
      >
        <el-form-item label="客户公司：">
          <el-input disabled v-model="form.hirerCompany" placeholder="请输入客户公司">
            <el-button style="background-color:#409EFF; color:#000" @click="openHirer" slot="append" icon="el-icon-search">选择业主公司</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="联系人姓名：">
          <el-input disabled v-model="form.hirerName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="身份证：">
          <el-input disabled v-model="form.hirerCard" placeholder="请输入" />
        </el-form-item>

        <!-- <el-form-item label="性别：">
          <el-input disabled v-model="form.hirerSex"  placeholder="请选择" />
        </el-form-item> -->

        <el-form-item label="联系方式：">
          <el-input disabled v-model="form.hirerPhone" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="从事的行业：">
          <el-input v-model="form.trade" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="详细说明: ">
          <el-input v-model="form.remark" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <el-tabs v-else>
        <el-tab-pane label="设置收费项目">
          <el-table v-if="this.form.type==0 && this.allId==''" :data="type0">
            <el-table-column
              type="index"
              label="序号"
              width="55"
              align="center"
            />
            <el-table-column
              label="收费项名"
              align="center"
              prop="name"
            />
            <el-table-column
              label="单价"
              align="center"
              prop="univalence"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['feeSettings:rentalcontract:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>


          <el-table v-else-if="this.form.type==1 && this.allId==''" :data="type1">
            <el-table-column
              type="index"
              label="序号"
              width="55"
              align="center"
            />
            <el-table-column
              label="收费项名"
              align="center"
              prop="name"
            />
            <el-table-column
              label="单价"
              align="center"
              prop="univalence"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['feeSettings:rentalcontract:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-table v-else :data="rc">
            <el-table-column
              type="index"
              label="序号"
              width="55"
              align="center"
            />
            <el-table-column
              label="收费项名"
              align="center"
              prop="chargeItemName"
            />
            <el-table-column
              label="单价"
              align="center"
              prop="chargeItemUnivalence"
            />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['feeSettings:rentalcontract:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <span
            @click="addFee"
            style="
              cursor: pointer;
              text-align: center;
              margin-top: 20px;
              margin-left: 50%;
            "
            >+ 增加收费项</span
          >
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="this.active !== 1"
          style="margin-top: 12px"
          @click="back"
          >上一步</el-button
        >
        <el-button
          v-if="this.active !== 3"
          style="margin-top: 12px"
          @click="next"
          >下一步</el-button
        >
        <el-button v-else style="margin-top: 12px" @click="commit"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <!-- 业主公司弹框 -->
    <el-dialog title="提示" :close-on-click-modal="false"  :visible.sync="hirerDialogVisible" width="50%">
      <el-form
        :model="hQueryParams"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="85px"
      >
        <el-form-item label="业主姓名" prop="name">
          <el-input
            v-model="hQueryParams.name"
            placeholder="请输入业主姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="身份证号码" prop="card">
          <el-input
            v-model="hQueryParams.card"
            placeholder="请输入身份证号码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="hHandleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="hResetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="hirerList">
        <el-table-column label="公司名" align="center" prop="company" />
        <el-table-column label="业主姓名" align="center" prop="name" />
        <el-table-column label="身份证号码" align="center" prop="card" />
        <el-table-column label="手机号码" align="center" prop="phone" />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_user_sex"
              :value="scope.row.sex"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="choose(scope.row.id)"
              v-hasPermi="['hirer:hirer:edit']"
              >选择业主</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="hQueryParams.pageNum"
        :limit.sync="hQueryParams.pageSize"
        @pagination="hGetList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button style="margin-top: 12px" @click="closeHirer">取消</el-button>
      </div>
    </el-dialog>

    <!-- 增加收费项 -->
    <el-dialog
      title="选择收费项"
      :visible.sync="addFeeDialogVisible"
      width="55%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="cQueryParams"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="85px"
      >
        <el-form-item label="项目名" prop="name">
          <el-input
            v-model="cQueryParams.name"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="cHandleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="cResetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="chargeitemList"
        @selection-change="cHandleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="收费项目名" align="center" prop="name" />
        <el-table-column label="单价" align="center" prop="univalence" />
        <el-table-column label="收费方式" align="center" prop="mode" />
        <el-table-column label="计算公式" align="center" prop="formula" />
        <el-table-column label="计算周期" align="center" prop="period" />
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="hQueryParams.pageNum"
        :limit.sync="hQueryParams.pageSize"
        @pagination="hGetList"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="qx">取 消</el-button>
        <el-button type="primary" @click="addRental">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 默认收费项 -->
    <el-dialog
      style="margin-top: 50px !important; height: 100%"
      width="55%"
      title="默认收费项"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
    >
      <el-dialog
        style="margin-top: 50px !important"
        custom-class="vDialog"
        width="40%"
        title="选择收费项"
        :visible.sync="innerVisible"
        append-to-body
        :close-on-click-modal="false"
      >
        <!-- 内层表格（选择收费项添加） -->
        <el-form :model="innerQueryInfo" size="small" :inline="true">
          <el-form-item label="关键词" prop="name">
            <el-input
              v-model="innerQueryInfo.name"
              placeholder="请输入"
              clearable
              @clear="innerSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="innerSearch"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="innerReset"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          max-height="300"
          :data="innerData"
          @selection-change="handleSelectionChargeItems"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="收费项目名" align="center" prop="name" />
          <el-table-column label="单价" align="center" prop="univalence" />
          <el-table-column label="收费方式" align="center" prop="mode" />
          <el-table-column label="计算公式" align="center" prop="formula" />
          <el-table-column label="计算周期" align="center" prop="period" />
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="innerCancel">取 消</el-button>
          <el-button type="primary" @click="innerConfirm">确 认</el-button>
        </div>
      </el-dialog>
      <el-table
        max-height="300"
        :data="hireOrSellList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" :index="1" label="序号">
        </el-table-column>
        <el-table-column
          property="name"
          label="收费项名"
          width="340"
        ></el-table-column>
        <el-table-column
          property="univalence"
          label="单价"
          width="350"
        ></el-table-column>
        <el-table-column property="address" width="60" label="操作">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteRow(scope.$index, hireOrSellList)"
              type="text"
              size="small"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-col style="text-align: center; height: 50px; line-height: 50px">
        <el-link @click="addHireOrSell" type="primary"
          ><i class="el-icon-plus"></i>添加收费项</el-link
        >
      </el-col>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveHireOrSell">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listRentalcontract,getRentalcontract,delRentalcontract,addRentalcontract,updateRentalcontract,getMap,updateState } from "@/api/feeSettings/rentalcontract";
import { selectListDowntown } from "@/api/asset/downtown";
import { listHirer,getHirer } from "@/api/hirer/hirer";
import { listChargeitem } from "@/api/feeSettings/chargeitem";
import { delCRental,addCRental,getByRid } from "@/api/feeSettings/cRental";
import { getShopsByDid, getShopsByDidAndCode,listShops } from "@/api/asset/shops";
import {
  getDefaultchargesByType,
  save,
} from "@/api/feeSettings/defaultcharges";

export default {
  name: "Rentalcontract",
  dicts: ["zhwy_rent", "sys_user_sex"],
  data() {
    return {
      download:{},
      //内层弹出框查询参数
      innerQueryInfo: {
        name: "",
      },
      //选中收费项数据
      selectedChargeItems: [],
      //内层弹出框收费项数据
      innerData: [],
      //内层弹出框
      innerVisible: false,
      //默认收费项弹出框
      dialogTableVisible: false,
      hireOrSellList: [],
      //出租0还是出售1
      flag : null,
      // 编辑合同全局id
      allId: "",
      // 获取商业区code
      codes: [],
      types: [
        { value: "0", label: "出租" },
        { value: "1", label: "出售" },
      ],
      downtownList: [],
      active: 1,
      dialogVisible: false,
      hirerDialogVisible: false,
      addFeeDialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 添加收费项选中数组
      cIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 非多个禁用
      cMultiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租售合同表格数据
      rentalcontractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopsId: null,
        type: null,
        hirerId: null
      },
      // 查询参数
      hQueryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        card: null,
        phone: null,
      },
      sQueryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        state: null,
        buildingName: null,
        buildingId: null
        },
      // 查询参数
      cQueryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        name: null,
      },
      // 用户收集表
      hirerList: [],
      // 收费项收集表
      chargeitemList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        shopsCode: [{
            required: true,
            message: "编号不能为空",
            trigger: "blur"
          }],
      },
      cRent: {},
      // 收费表的数据
      rc: [],
      //全局完整编号数组
      codeArr:[],
      type0:[],
      type1:[],
      type0Ids:[],
      type1Ids:[],
      editId:[]
    };
  },
  created() {
    this.getList();
    this.dGetList();
    this.hGetList();
    this.getType0();
    this.getType1()
  },
  methods: {
    // 撤销合同
    putState(row){
       this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {updateState(row.id).then(response=>{
        this.$message.success("撤销成功")
        this.getList()
      })
      })

    },
    //内层对话框确认，将数据添加到外层对话框表格数据
    innerConfirm() {
      // 使用 map 方法将 selectedChargeItems 数组中每个对象的 id 属性修改为 chargeitemId
      let modifiedSelectedChargeItems = this.selectedChargeItems
        .map((item) => {
          return { chargeitemId: item.id, ...item };
        })
        .map(function (obj) {
          // 使用对象的解构赋值语法复制除了 id 之外的其他属性到新的对象中
          var { id, ...rest } = obj;
          // 返回新的对象，不包含 id 属性
          return rest;
        });
      // 遍历 modifiedSelectedChargeItems 数组，并将每一项添加到 hireOrSellList 数组中
      modifiedSelectedChargeItems.forEach((item) => {
        this.hireOrSellList.push(item);
      });
      this.innerVisible = false;
    },
    // 内层对话框搜索
    innerSearch() {
      listChargeitem(this.innerQueryInfo).then((response) => {
        this.innerData = response.rows;
      });
    },
    //内层对话框重置
    innerReset() {
      this.innerQueryInfo = {
        name: "",
      };
    },
    //内层对话框取消
    innerCancel() {
      this.innerVisible = false;
      this.innerReset();
    },
    //处理选中行数据
    handleSelectionChargeItems(val) {
      this.selectedChargeItems = val;
      // this.selectedChargeItems = val.map((item) => item.id);
      console.log(this.selectedChargeItems);
    },
    //点击添加收费项按钮
    addHireOrSell() {
      this.innerVisible = true;
      this.innerSearch();
    },
    //
    saveHireOrSell() {
      let list = this.hireOrSellList;
      let f = this.flag;
      let params = {
        hireOrSellList:list,
        flag : f
      }
      save(params).then((response) => {
        if (response.data == 200) {
          this.$message.success({
            message: "保存成功",
            duration: 1000,
          });
          this.dialogTableVisible = false;
        }
      });
    },
    //移除
    deleteRow(index, rows) {
      rows.splice(index, 1);
      console.log(this.hireOrSellList);
    },
    //获取收费项数据(出租出售)
    // getHireList(id) {},

    // 根据类型渲染数据
    getType0(){
      getDefaultchargesByType(0).then((response) => {
        // console.log("type=====0");
        //   console.log(response.data);
          this.type0 = response.data;
          for (let i = 0; i < response.data.length; i++) {
            this.type0Ids[i] = response.data[i].chargeitemId
          }
          // console.log(this.type0Ids);
        });
    },
        // 根据类型渲染数据
    getType1(){
      getDefaultchargesByType(1).then((response) => {
        // console.log("type=====1");
          // console.log(response.data);
          this.type1 = response.data;
          for (let i = 0; i < response.data.length; i++) {
            this.type1Ids[i] = response.data[i].chargeitemId
          }
        });
    },
    //默认收费项
    addHire(id) {
      if (id == 0) {
        this.flag = 0;
        this.dialogTableVisible = true;
        //获取收费项数据(出租出售)
        getDefaultchargesByType(id).then((response) => {
          console.log(response.data);
          this.hireOrSellList = response.data;
        });
      } else {
        this.flag = 1;
        this.dialogTableVisible = true;
        //获取收费项数据(出租出售)
        getDefaultchargesByType(id).then((response) => {
          console.log(response.data);
          this.hireOrSellList = response.data;
        });
      }
    },
    // 渲染合同中的收费项信息
    getCRen(id) {
      getByRid(id).then((response) => {
        // console.log(response);
        this.rc = response;
      });
    },
    // 编辑合同
    handleEdit(row) {
      if(!this.editId.includes(row.id)){
       if(row.type==0){
        for (let i = 0; i < this.type0Ids.length; i++) {
        this.cRent.chargeitemId = this.type0Ids[i];
        this.cRent.rentalcontractId = row.id;
        addCRental(this.cRent).then((response) => {
          console.log(response);
        });
      }
      } else{
        for (let i = 0; i < this.type1Ids.length; i++) {
        this.cRent.chargeitemId = this.type1Ids[i];
        this.cRent.rentalcontractId = row.id;
        addCRental(this.cRent).then((response) => {
          
          console.log(response);
        });
      }
      }
      this.editId.push(row.id)
      this.download={}
      this.sQueryParams.code=row.shopsCode
      this.active = 1
      this.reset();
      this.open = true;
      this.allId = row.id;
      this.form.id = row.id;
      this.getCRen(this.allId);
      const id = row.id || this.ids;
      getRentalcontract(id).then((response) => {
        this.form = response.data;
        this.title = "修改租售合同";
      });
      listShops(this.sQueryParams).then(res=>{
        console.log(res.rows[0]);
        this.download=res.rows[0]
      })
      }
      this.download={}
      this.sQueryParams.code=row.shopsCode
      this.active = 1
      this.reset();
      this.open = true;
      this.allId = row.id;
      this.form.id = row.id;
      this.getCRen(this.allId);
      const id = row.id || this.ids;
      getRentalcontract(id).then((response) => {
        this.form = response.data;
        this.title = "修改租售合同";
      });
      listShops(this.sQueryParams).then(res=>{
        console.log(res.rows[0]);
        this.download=res.rows[0]
      })
    },

    // 添加收费项按钮
    addRental() {
      for (let i = 0; i < this.cIds.length; i++) {
        this.cRent.chargeitemId = this.cIds[i];
        this.cRent.rentalcontractId = this.allId;
        addCRental(this.cRent).then((response) => {
          console.log(response);
        });
      }
      this.active === 3;
      this.addFeeDialogVisible = false;
      this.open = true;
      this.getCRen(this.allId);
    },

    // 选择业主
    choose(id) {
      getHirer(id).then((response) => {
        console.log(response.data);
        this.form.hirerCompany = response.data.company;
        this.form.hirerName = response.data.name;
        this.form.hirerCard = response.data.card;
        this.form.hirerSex = response.data.sex;
        this.form.hirerPhone = response.data.phone;
        this.form.hirerId = response.data.id;
        this.hirerDialogVisible = false;
        this.open = true;
        this.active === 2;
      });
    },
    // 根据商业名和完整编号获取租金
    codesGetList() {
      console.log(this.form.dId);
      console.log(this.form.shopsCode);
      getShopsByDidAndCode(this.form.dId, this.form.shopsCode).then(
        (response) => {
          console.log(response);
          for (let i = 0; i < response.length; i++) {
            this.form.rent = response[i].rentFree;
            this.form.shopsId = response[i].id;
          }
        }
      );
    },
    // 获取添加合同数据
    sGetList() {
      console.log(this.form.dId);
      getShopsByDid(this.form.dId).then((response) => {
        this.codes = response;
        // for (let i = 0; i < response.length; i++) {
        //   if(!this.codeArr.includes(response[i].code)){
        //     this.codes[i].label = response[i].code;
        //     this.codes[i].value = response[i].code;
        //   }
        // }


         // 使用filter方法来过滤掉已经存在于this.codeArr中的code  
        this.codes = response.filter(item => !this.codeArr.includes(item.code));  
  
         // 现在this.codes中只包含新的code，我们可以安全地设置label和value  
        for (let i = 0; i < this.codes.length; i++) {  
          this.codes[i].label = this.codes[i].code;  
          this.codes[i].value = this.codes[i].code;  
        }  
        
      });
    },

    /** 查询收费项管理列表 */
    cGetList() {
      this.loading = true;
      this.cQueryParams.type = 0;
      listChargeitem(this.cQueryParams).then((response) => {
        this.chargeitemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 增加收费项取消按钮
    qx() {
      this.active === 3;
      this.addFeeDialogVisible = false;
      this.open = true;
    },
    // 增加收费项
    addFee() {
      this.addFeeDialogVisible = true;
      this.open = false;
      this.cGetList();
    },
    /** 查询租户信息列表 */
    hGetList() {
      this.loading = true;
      listHirer(this.hQueryParams).then((response) => {
        this.hirerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 打开公司弹框
    openHirer() {
      this.open = false;
      this.hirerDialogVisible = true;
    },
    // 选择业主信息取消按钮
    closeHirer() {
      this.hirerDialogVisible = false;
      this.open = true;
      this.active === 2;
    },
    /** 查询商业区信息列表 */
    dGetList() {
      selectListDowntown().then((response) => {
        this.downtownList = response;
        for (let i = 0; i < response.length; i++) {
          this.downtownList[i].label = response[i].name;
          this.downtownList[i].value = response[i].id;
        }
      });
    },
    next() {
      if (this.active++ > 2) this.active = 0;
    },

    back() {
      if (this.active-- < 0) this.active = 2;
    },
    /** 查询租售合同列表 */
    getList() {
      this.loading = true;
      listRentalcontract(this.queryParams).then((response) => {
        this.rentalcontractList = response.rows;
        for (let i = 0; i < this.rentalcontractList.length; i++) {
          if(this.rentalcontractList[i].state!=1){
            this.codeArr[i]=this.rentalcontractList[i].shopsCode
          }
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopsId: null,
        type: null,
        hirerId: null,
        rent: null,
        trade: null,
        remark: null,
        startTime: null,
        taxi: null,
        endTime: null,
        state: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 搜索按钮操作 */
    cHandleQuery() {
      this.cQueryParams.pageNum = 1;
      this.cGetList();
    },
    /** 重置按钮操作 */
    cResetQuery() {
      // this.resetForm("queryForm");
      this.cHandleQuery();
    },

    /** 重置按钮操作 */
    hResetQuery() {
      this.hHandleQuery();
    },
    /** 搜索按钮操作 */
    hHandleQuery() {
      this.hQueryParams.pageNum = 1;
      this.hGetList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 收费项选中数据
    cHandleSelectionChange(selection) {
      this.cIds = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.cMultiple = !selection.length;
      console.log(this.cIds);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.allId=''
      this.reset();
      this.open = true;
      this.reset();
      this.active = 1;
      this.title = "添加租售合同";
    },
    // /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset();
    //   const id = row.id || this.ids
    //   getRentalcontract(id).then(response => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "修改租售合同";
    //   });
    // },
    /** 提交按钮 */
    commit() {
      if (this.form.id != null) {
        this.active === 1;

        updateRentalcontract(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.active === 1;
          this.open = false;

          this.getList();
        });
      } else {
        this.active === 0;
        addRentalcontract(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.active === 1;
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除租售合同编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCRental(ids);
        })
        .then(() => {
          this.getCRen(this.allId);
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "feeSettings/rentalcontract/export",
        {
          ...this.queryParams,
        },
        `rentalcontract_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.vDialog .el-dialog__body {
  padding-top: 0px !important;
}
</style>
